package com.wehealth.electrocardiograph_two_client.db;


import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;


import com.wehealth.electrocardiograph_two_client.model.PatientUser;

import java.util.ArrayList;
import java.util.List;

public class PatientUserDao {

	public static final String TABLE_NAME = "patient_user";
	public static final String COLUMN_NAME_CARD_ID = "patient_user_pid";
	public static final String COLUMN_NAME_AGE = "patient_user_age";
	public static final String COLUMN_NAME_GENDER = "patient_user_gender";
	public static final String COLUMN_NAME_NAME = "patient_user_name";
	public static final String COLUMN_NAME_UPDATE_TIME = "patient_user_update_time";

	private DbOpenHelper dbHelper;
	private static PatientUserDao patInstance;

	public static PatientUserDao getInstance(){
		if (patInstance==null) {
			patInstance = new PatientUserDao();
		}
		return patInstance;
	}

	public PatientUserDao() {
		dbHelper = DbOpenHelper.getInstance();
	}

	public synchronized void savePatientUser(PatientUser pu){
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		try {
			db.beginTransaction();
			if(db.isOpen()){
				ContentValues values = new ContentValues();
				values.put(COLUMN_NAME_CARD_ID, pu.getIdCardNo());
				values.put(COLUMN_NAME_NAME, pu.getName());
				values.put(COLUMN_NAME_AGE, pu.getAge());
				values.put(COLUMN_NAME_GENDER, pu.getGender());
				values.put(COLUMN_NAME_UPDATE_TIME,pu.getUpdateTime());
				if (checkIdExists(pu.getIdCardNo())) {
					updatePatientUser(pu);
				}else {
					long id = db.insert(TABLE_NAME, null, values);
					System.out.println("insert ："+id);
				}
			}
			db.setTransactionSuccessful();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if (db!=null) {
				db.endTransaction();
				System.out.println("结束事务");
			}
		}
	}

	public PatientUser getPatientUserByPatId(String tpId){
		if (TextUtils.isEmpty(tpId)){
			return null;
		}
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		PatientUser rd = null;
		if(db.isOpen()){
			Cursor cursor = db.rawQuery("select * from " + TABLE_NAME + " where "+ COLUMN_NAME_CARD_ID+" = ?", new String[]{tpId});
			if (cursor.moveToFirst()) {
				rd = new PatientUser();
				String patId = cursor.getString(cursor.getColumnIndex(COLUMN_NAME_CARD_ID));
				String name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME_NAME));
				int age = cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_AGE));
				int gender = cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_GENDER));
				long updateTime = cursor.getLong(cursor.getColumnIndex(COLUMN_NAME_UPDATE_TIME));

				rd.setIdCardNo(patId);
				rd.setName(name);
				rd.setAge(age);
				rd.setGender(gender);
				rd.setName(name);
				rd.setUpdateTime(updateTime);
			}
			cursor.close();
		}
		return rd;
	}

	public boolean checkIdExists(String id){
		boolean isExists = false;
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		if (db.isOpen()) {
			Cursor cursor = db.rawQuery("select count(*) from "+TABLE_NAME+" where "+COLUMN_NAME_CARD_ID+" = ? ", new String[]{id});
			cursor.moveToFirst();
			long count = cursor.getLong(0);
			if (count>0) {
				isExists = true;
			}
			cursor.close();
		}

		return isExists;
	}

	/**获取最近十条的用户信息**/
	public List<String[]> get10UserIDs(){
		List<String[]> list = new ArrayList<>();
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		if(db.isOpen()){
			Cursor cursor = db.query(TABLE_NAME, new String[]{COLUMN_NAME_CARD_ID, COLUMN_NAME_NAME}, null, null, null, null, COLUMN_NAME_UPDATE_TIME+" desc", "10");
			while (cursor.moveToNext()) {
				String patId = cursor.getString(cursor.getColumnIndex(COLUMN_NAME_CARD_ID));
				String patName = cursor.getString(cursor.getColumnIndex(COLUMN_NAME_NAME));

				String[] str = new String[]{patId, patName};
				list.add(str);
			}
			cursor.close();
		}
		return list;
	}

	/**
	 * 更新Device
	 * @param id
	 * @param values
	 */
	private void updatePatientUser(String id, ContentValues values){
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		try {
			db.beginTransaction();
			if(db.isOpen()){
				int a = db.update(TABLE_NAME, values, COLUMN_NAME_CARD_ID + " = ?", new String[]{id});
				System.out.println("update : "+a);
			}
			db.setTransactionSuccessful();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if (db!=null) {
				db.endTransaction();
			}
		}
	}

	public void updatePatientUser(PatientUser pu){
		ContentValues values = new ContentValues();
		values.put(COLUMN_NAME_NAME, pu.getName());
		values.put(COLUMN_NAME_AGE, pu.getAge());
		values.put(COLUMN_NAME_GENDER, pu.getGender());
		values.put(COLUMN_NAME_CARD_ID, pu.getIdCardNo());
		values.put(COLUMN_NAME_UPDATE_TIME, pu.getUpdateTime());
		updatePatientUser(pu.getIdCardNo(), values);
	}

	public void deletePatientUserById(String id){
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		if(db.isOpen()){
			db.delete(TABLE_NAME, COLUMN_NAME_CARD_ID + " = ?", new String[]{id});
		}
	}

	public void reset(){
		if (patInstance!=null) {
			patInstance = null;
		}
	}
}
